﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Foxit.PDF;
using Sustainalytics.AwsS3.Client;
using Sustainalytics.Entities.RiskRatings;
using Sustainalytics.Utils.Configuration;

namespace Sustainalytics.RiskRatings.Reporting
{
    public enum VerticalSpacing
    {
        Large = 16,
        Small = 8
    }

    public enum HorisontalSpacing
    {
        Large = 25,
        Medium = 15
    }

    public enum TextSizes
    {
        SectionTitle = 11,
        SubSectionTitle = 9,
        RegularText = 7,
        RegularTextSubtitle = 9,
        SmallText = 6,
    }

    public enum HeaderTextSizes
    {
        HeaderCompanyName = 20,
        HeaderReportTitle = 9,
        HeaderRisk = 16,
        HeaderMeiTitle = 16
    }

    public enum RiskRatingTypes
    {
        RiskExposure,
        ManagedRisk,
        UnmanagedRisk,
        Universe,
        SubIndustry
    }

    public static class ReportHelper
    {
        static ConcurrentDictionary<string, byte[]> S3ImagesList;
        public static Dictionary<RiskRatingClusterAssessment?, RgbColor> RiskClusterColors { get; set; }
        public static Dictionary<RiskRatingTypes, RgbColor> RiskRatingTypesColors { get; set; }
        private static readonly string _bucketName;
        private static readonly string _prefix;

        static ReportHelper()
        {
            _bucketName = SettingsHelper.Read("s3-risk-rating-images", "risk-rating-images");
            _prefix = SettingsHelper.Read("s3prefix-risk-rating-images", "Dev");

            LoadS3Images();
            LoadUnmanagedRiskColors();
            LoadRiskRatingTypesColors();
        }

        public static void Initialize()
        {         
        }

        public static string AddOrdinal(int num)
        {
            if (num <= 0) return num.ToString();

            switch (num % 100)
            {
                case 11:
                case 12:
                case 13:
                    return num + "th";
            }

            switch (num % 10)
            {
                case 1:
                    return num + "st";
                case 2:
                    return num + "nd";
                case 3:
                    return num + "rd";
                default:
                    return num + "th";
            }

        }

        private static void LoadRiskRatingTypesColors()
        {
            RiskRatingTypesColors = new Dictionary<RiskRatingTypes, RgbColor>();
            RiskRatingTypesColors.Add(RiskRatingTypes.RiskExposure, new RgbColor(180, 213, 209));
            RiskRatingTypesColors.Add(RiskRatingTypes.ManagedRisk, new RgbColor(167, 169, 172));
            RiskRatingTypesColors.Add(RiskRatingTypes.UnmanagedRisk, RgbColor.Black);
            RiskRatingTypesColors.Add(RiskRatingTypes.SubIndustry, RgbColor.Orange);
            RiskRatingTypesColors.Add(RiskRatingTypes.Universe, RgbColor.DarkGray);
        }

        private static void LoadUnmanagedRiskColors()
        {
            RiskClusterColors = new Dictionary<RiskRatingClusterAssessment?, RgbColor>();
            RiskClusterColors.Add(RiskRatingClusterAssessment.Negligible, new RgbColor(252, 238, 204));
            RiskClusterColors.Add(RiskRatingClusterAssessment.Low, new RgbColor(249, 221, 153));
            RiskClusterColors.Add(RiskRatingClusterAssessment.Medium, new RgbColor(246, 205, 102));
            RiskClusterColors.Add(RiskRatingClusterAssessment.High, new RgbColor(243, 188, 51));
            RiskClusterColors.Add(RiskRatingClusterAssessment.Severe, new RgbColor(240, 171, 0));
        }

        public static void LoadS3Images()
        {
            if (S3ImagesList == null)
            {
                S3ClientSettings _s3ClientSettings;

                S3ImagesList = new ConcurrentDictionary<string, byte[]>();
                _s3ClientSettings = new S3ClientSettings
                {
                    AccessKey = SettingsHelper.Read("accesKeyId", "AKIAJKGZZMOFAVOVLHJA"),
                    SecretAccessKey = SettingsHelper.Read("awsSecretKey", "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"),
                    ServiceEndPoint = SettingsHelper.Read("s3ServiceEndPoint", "https://s3-eu-west-1.amazonaws.com/")
                };

                using (var s3Client = new S3Client(_s3ClientSettings))
                {
                    var sourceFileKeys = s3Client.GetS3Objects(_bucketName, _prefix).Select(x => x.Key);
                    foreach (var fileKey in sourceFileKeys)
                    {
                        try
                        {
                            byte[] imageByteArray = s3Client.DownloadFile(_bucketName, fileKey);
                            if (imageByteArray.Length > 0)
                                S3ImagesList.GetOrAdd(fileKey, imageByteArray);
                        }
                        catch (Exception) { }
                    }
                }
            }
        }

        public static byte[] LoadS3Image(string fileName)
        {
            fileName = $"{_prefix}/{fileName}";
            byte[] imageByteArray = new byte[0];

            S3ClientSettings _s3ClientSettings;

            _s3ClientSettings = new S3ClientSettings
            {
                AccessKey = SettingsHelper.Read("accesKeyId", "AKIAJKGZZMOFAVOVLHJA"),
                SecretAccessKey = SettingsHelper.Read("awsSecretKey", "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"),
                ServiceEndPoint = SettingsHelper.Read("s3ServiceEndPoint", "https://s3-eu-west-1.amazonaws.com/")
            };

            using (var s3Client = new S3Client(_s3ClientSettings))
            {
                try
                {
                    imageByteArray = s3Client.DownloadFile(_bucketName, fileName);
                        
                }
                catch (Exception) { }
            }

            return imageByteArray;
        }
        public static byte[] GetOutlookImage(string outlook)
        {
            byte[] imageArray = null;
            string fileName = $"{_prefix}/{outlook}.png";
            if (S3ImagesList.ContainsKey(fileName))
            {
                imageArray = S3ImagesList[fileName];
            }
            else
            {
                imageArray = LoadS3Image(fileName);
                S3ImagesList.GetOrAdd(outlook, imageArray);
            }
            return imageArray;
        }

        public static byte[] GetMeiImage(string externalId, MeiImageColor color, MeiImageSize size)
        {
            return GetMeiImage(externalId, color, size, false);
        }
        public static byte[] GetMeiImage(string externalId, MeiImageColor color, MeiImageSize size, bool isIdio)
        {
            byte[] imageArray = null;
            if (S3ImagesList != null)
            {
                string fileName = $"{_prefix}/{(isIdio ? "999" : externalId)}_{color.ToString().ToLower()}_{size.ToString().ToLower()}.png";
                imageArray = S3ImagesList.ContainsKey(fileName) ? S3ImagesList[fileName] : S3ImagesList[fileName.Replace(externalId, "99")];
            }
            return imageArray;
        }

        public static byte[] GetFile(string fileName)
        {
            byte[] imageArray = null;
            fileName = $"{_prefix}/{fileName}";

            if (S3ImagesList != null)
            {
                imageArray = S3ImagesList.ContainsKey(fileName) ? S3ImagesList[fileName] : null;
            }
            return imageArray;
        }


        public static byte[] GetEventImage(int answerCategoryId)
        {
            byte[] imageArray = null;

            var answerCategory = "0";
            if (answerCategoryId <= 5)
            {
                answerCategory = answerCategoryId.ToString();
            }

            string fileName = $"{_prefix}/icon_event_cat_{answerCategory}_large.png";

            if (S3ImagesList.ContainsKey(fileName))
            {
                imageArray = S3ImagesList[fileName];
            }
            else
            { 
                imageArray = LoadS3Image(fileName);
                S3ImagesList.GetOrAdd(answerCategory, imageArray);
            }
            return imageArray;
        }
    }
}
